/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id: maintabwidget.cpp 599 2010-06-04 21:36:49Z jpnurmi $
*/

#include "maintabwidget.h"
#include "application.h"
#include "settings.h"
#include <QShortcut>
#include <QTabBar>
#include <QMovie>

MainTabWidget::MainTabWidget(QWidget* parent) : TabWidget(parent)
{
    setTabPosition(QTabWidget::West);
    setStyleSheet(".MainTabWidget::pane { border: 0px; }");

    QIcon icon(":/resources/oxygen/16x16/actions/bookmark.png");
    setAlertIcon(icon);
    setHighlightIcon(icon);
    QMovie* animation = new QMovie(":/resources/ajax-loader.gif", "GIF", this);
    setAnimation(animation);

    d.tabUpShortcut = new QShortcut(this);
    connect(d.tabUpShortcut, SIGNAL(activated()), this, SLOT(moveToPrevTab()));

    d.tabDownShortcut = new QShortcut(this);
    connect(d.tabDownShortcut, SIGNAL(activated()), this, SLOT(moveToNextTab()));

#if QT_VERSION >= 0x040600
    registerSwipeGestures(Qt::Vertical);
#endif

    connect(qApp, SIGNAL(settingsChanged()), this, SLOT(applySettings()));
    applySettings();
}

void MainTabWidget::tabInserted(int index)
{
    Q_UNUSED(index);
    tabBar()->setVisible(count() > 1);
}

void MainTabWidget::tabRemoved(int index)
{
    Q_UNUSED(index);
    tabBar()->setVisible(count() > 1);
}

void MainTabWidget::applySettings()
{
    Settings settings = Application::settings();
    d.tabUpShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabUp)));
    d.tabDownShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabDown)));
}

void MainTabWidget::setSessionTitle(const QString& title)
{
    int index = senderIndex();
    if (index != -1)
        setTabText(index, title);
}

void MainTabWidget::activateAlert(bool active)
{
    int index = senderIndex();
    if (index != -1)
        setTabAlert(index, active);
}

void MainTabWidget::activateHighlight(bool active)
{
    int index = senderIndex();
    if (index != -1)
        setTabHighlight(index, active);
}

int MainTabWidget::senderIndex() const
{
    if (!sender() || !sender()->isWidgetType())
        return -1;

    return indexOf(static_cast<QWidget*>(sender()));
}
